package engine

import (
	"context"
	"errors"
	"fmt"
	"log"
	"strings"

	"github.com/androidsr/sc-go/sgorm"
	"github.com/androidsr/sc-go/syaml"
	"github.com/tmc/langchaingo/tools/sqldatabase"
)

type MysqlEngine struct {
	db     *sgorm.Sgorm
	dbname string
}

func NewMysqlEngine(dsn, dbname string) sqldatabase.Engine {
	engine := &MysqlEngine{}
	engine.db = sgorm.New(&syaml.GormInfo{
		Driver:  "mysql",
		Url:     dsn,
		MaxOpen: 3,
		MaxIdle: 1,
		ShowSql: true,
	})
	engine.dbname = dbname
	return engine
}

func (engine *MysqlEngine) Dialect() string {
	return "mysql"
}

func (engine *MysqlEngine) Query(ctx context.Context, query string, args ...any) (cols []string, results [][]string, err error) {
	result := make([]map[string]interface{}, 0)
	err = engine.db.Raw(query, args...).Scan(&result).Error
	if err != nil {
		return nil, nil, err
	}
	if len(result) == 0 {
		return nil, nil, errors.New("数据为空")
	}
	for i, item := range result {
		lines := make([]string, 0)
		for k, v := range item {
			if i == 0 {
				cols = append(cols, k)
			}
			lines = append(lines, fmt.Sprint(v))
		}
		results = append(results, lines)
	}
	log.Println(cols, results)

	return cols, results, nil
}

func (engine *MysqlEngine) TableNames(ctx context.Context) ([]string, error) {
	result := make([]string, 0)
	err := engine.db.Raw(fmt.Sprintf("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '%s'", engine.dbname)).Scan(&result).Error
	log.Println(result)
	return result, err
}

func (engine *MysqlEngine) TableInfo(ctx context.Context, tables string) (string, error) {
	result := make([]string, 0)
	err := engine.db.Raw(fmt.Sprintf("select  column_name from information_schema.columns where table_name='%s' and table_schema='%s'", tables, engine.dbname)).Scan(&result).Error
	if err != nil {
		return "", err
	}
	str := strings.Join(result, "\t")
	log.Println(str)
	return str, nil
}

func (engine *MysqlEngine) Close() error {
	return nil
}
